package sm.upgrade;

import java.util.List;
import java.util.ListIterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import sm.codec.type.NullValue;
import sm.upgrade.api.UpgradePhase;
import sm.util.SMMap;

public class KMOperatorUpgrade implements UpgradePhase {

	private static Logger logger = LoggerFactory.getLogger(UpgradePhase.class);

	private HibernateTemplate template;

	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}

	private void removeEmptyItem(List<Object> list) {
		if (list != null) {
			for (ListIterator<Object> it = list.listIterator(); it.hasNext();) {
				Object value = it.next();
				if (value == null || value instanceof NullValue
						|| "".equals(value)) {
					it.remove();
				}
			}
		}
	}

	@Override
	public void upgrade() {
		logger.info("Updating operator records for KM...");

		List<Object> operators = template.find("from operator");

		for (Object operator : operators) {
			SMMap operatorMap = (SMMap) operator;
			Object capExecs = operatorMap.get("cap_exec");
			if (capExecs instanceof List) {
				List<Object> capExecsList = (List<Object>) capExecs;
				if (capExecsList.size() == 1) {
					Object capExec = capExecsList.get(0);
					// Begin modified by LiuYongliang for QCCR1E64831
					List<Object> srarray = (List<Object>) operatorMap
							.get("secRole");
					List<Object> cearray = (List<Object>) operatorMap
							.get("cap_exec");
					removeEmptyItem(srarray);
					removeEmptyItem(cearray);
					if ("SysAdmin".equals(capExec) && srarray != null
							&& !srarray.contains("system administrator")) {
						srarray.add("system administrator");
						template.update("operator", operatorMap);
					}
					if ("KMAdmin".equals(capExec) && cearray != null
							&& !cearray.contains("knowledge administrator")) {
						cearray.add("knowledge administrator");
						template.update("operator", operatorMap);
					}
				}
			}
		}

		logger.info("  Finished updating operator records for KM.");

	}
}
